# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : running_count_view.py
# Time       ：2023/11/2 16:15
# Author     ：YangYong
# version    ：python 3.10
# Description：运行次数对比
"""
from datetime import datetime, timedelta

from flask_restx import Resource
from sqlalchemy import func, extract

from apis.data_screen import data_screen_ns
from apis.data_screen.schema.running_count_schema import RunningCountSchema
from apis.orderlines.models import ProcessInstance
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response


class RunningCountView(Resource):
    url = '/running_count'

    def __init__(self, *args, **kwargs):
        super(RunningCountView, self).__init__(*args, **kwargs)
        self.current_filter = list()
        self.last_filter = list()
        self.current_data = f"{datetime.now().strftime('%Y-%m-%d')} 23.59.59"
        self.current_week = f"{(datetime.now() - timedelta(days=7)).strftime('%Y-%m-%d')} 23.59.59"
        self.last_week = f"{(datetime.now() - timedelta(days=14)).strftime('%Y-%m-%d')} 23.59.59"

    @staticmethod
    def get_running_count(filter_list):
        objs = db.session.query(
            extract('day', ProcessInstance.start_time).label('date'),
            func.count(1).label('value')
        ).group_by('date').filter(*filter_list).all()
        info = RunningCountSchema().dump(objs, many=True)
        week_data = list()
        for item in info:
            week_data.append(item.get('value'))
        if len(week_data) != 7:
            week_data += [0 for _ in range(7 - len(week_data))]
        return [str(item) for item in week_data]

    @handle_api_error()
    @data_screen_ns.doc(description='运行次数对比')
    def get(self):
        """运行次数对比"""
        self.current_filter.append(ProcessInstance.start_time.between(self.current_week, self.current_data))
        self.last_filter.append(ProcessInstance.start_time.between(self.last_week, self.current_week))
        current_week = self.get_running_count(self.current_filter)
        last_week = self.get_running_count(self.last_filter)
        data = [
            {'label': '本周', 'value': current_week},
            {'label': '上周', 'value': last_week}
        ]
        response_data = {
            'data': data,
            'unit': ['本周', '上周'],
            'columns': ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            'colors': ["#007AFE", "#FF4B7A"]
        }

        return generate_response(response_data)
